package com.ny.controller;

import com.ny.entity.Classrooms;
import com.ny.entity.Reservations;
import com.ny.entity.Users;
import com.ny.service.ClassroomService;
import com.ny.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class ApplyController {
    @Autowired
    private ClassroomService classroomService;
    @Autowired
    private ReservationService reservationService;
    // 申请界面
    @GetMapping("/apply")
    public String applyPage(@RequestParam int classroomId, @RequestParam int userId, Model model) {
        model.addAttribute("classroomId", classroomId);
        model.addAttribute("userId", userId);
        return "apply";
    }

    // 申请功能
    @PostMapping("/submitApply")
    public String submitApply(@RequestParam int classroomId,
                              @RequestParam int userId,
                              @RequestParam String startTime,
                              @RequestParam String endTime,
                              @RequestParam String reason) throws ParseException {
//   一、申请成功：     1.修改该教室的状态:可用，申请中，不可用  2.预约表添加一条预约功能。 3.审批之后再改变教室状态和预约表的状态
//        1.修改该教室的状态
        classroomService.updateClassroomStatusById(classroomId, "申请中");
//        2.预约表添加一条预约功能。
        Reservations reservation = new Reservations();
        Users user = new Users();
        user.setUserId(userId);
        reservation.setUser(user);

        Classrooms classrooms = new Classrooms();
        classrooms.setClassroomId(classroomId);
        reservation.setClassroom(classrooms);
        reservation.setReason(reason);
        reservation.setStatus("申请中");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
        reservation.setStartDatetime(sdf.parse(startTime));
        reservation.setEndDatetime(sdf.parse(endTime));
//        把数据交给 Service
        reservationService.addReservation(reservation);
//        List<Classrooms> classroomsList = classroomService.findAllClassrooms();
//        System.out.println(classroomsList);
//        model.addAttribute("classroomList", classroomsList);
        return "forward:/classroomList";
    }
}
